Anonymous inner class

Course- Java >

A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:

Class (may be abstract or concrete).

Interface

Java anonymous inner class example using class

abstract class Person{  

  abstract void eat();  

}  

class TestAnonymousInner{  

 public static void main(String args[]){  

  Person p=new Person(){  

  void eat(){System.out.println("nice fruits");}  

  };  

  p.eat();  

 }  

}  

 

Output:

nice fruits

Internal working of given code

Person p=new Person(){  

void eat(){System.out.println("nice fruits");}  

};  

A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.

An object of Anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler

import java.io.PrintStream;  

static class TestAnonymousInner$1 extends Person  

{  

   TestAnonymousInner$1(){}  

   void eat()  

    {  

        System.out.println("nice fruits");  

    }  

}  

Java anonymous inner class example using interface

interface Eatable{  

 void eat();  

}  

class TestAnnonymousInner1{  

 public static void main(String args[]){  

 Eatable e=new Eatable(){  

  public void eat(){System.out.println("nice fruits");}  

 };  

 e.eat();  

 }  

}  

 

Output:

nice fruits

Internal working of given code

It performs two main tasks behind this code:

Eatable p=new Eatable(){  

void eat(){System.out.println("nice fruits");}  

};  

A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method.

An object of Anonymous class is created that is referred by p reference variable of Eatable type.

Internal class generated by the compiler

import java.io.PrintStream;  

static class TestAnonymousInner1$1 implements Eatable  

{  

TestAnonymousInner1$1(){}  

void eat(){System.out.println("nice fruits");}  

}